package com.xgure.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.xgure.properties.JwtProperties;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Map;

/**
 * jwt工具类
 */
@Component
public class JwtUtil {

    @Resource
    private JwtProperties jwtProperties;

    /**
     * 生成jwt令牌
     * @param secret 密钥
     * @param claims 自定义数据
     * @return jwt令牌
     */
    public String generateToken(String secret, Map<String, String> claims) {
        Calendar instance = Calendar.getInstance();

        instance.add(Calendar.MILLISECOND, jwtProperties.getExpiration());

        JWTCreator.Builder builder = JWT.create();

        claims.forEach(builder::withClaim);

        // 返回令牌
        return builder.withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(secret));
    }

    /**
     * 验证jwt令牌
     * @param token 令牌
     * @param secret 密钥
     * @return 解码后的jwt令牌
     */
    public DecodedJWT verifyToken(String token, String secret) {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secret)).build();
        return verifier.verify(token);
    }

}
